﻿using log4net.Core;
using log4net.Layout;
using log4net.Layout.Pattern;
using System.IO;
using System.Reflection;

namespace DLMemberPointMS.Web.Configs
{
    public class LogContent
    {
        public string job_code { get; set; }
        public string stream_id { get; set; }
        /// <summary>
        /// 自定义日志类  对应数据库表字段
        /// </summary>


        public class CustomLoyout : PatternLayout
        {
            public CustomLoyout()
            {
                this.AddConverter("property", typeof(LogInfoPatternConverter));
            }
        }

        public class LogInfoPatternConverter : PatternLayoutConverter
        {
            protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
            {
                if (Option != null)
                {
                    WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
                }
                else
                {
                    WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
                }
            }

            /// <summary>
            /// 反射获取传入日志对象的某个属性的值
            /// </summary>
            /// <param name="property"></param>
            /// <param name="loggingEvent"></param>
            /// <returns></returns>
            private object LookupProperty(string property, LoggingEvent loggingEvent)
            {
                object propertyValue = string.Empty;
                PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);

                if (property != null)
                {
                    propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
                }
                return propertyValue;
            }
        }
    }
}